<template>
  <div>
    <Card>
      <tables ref="tables" editable searchable search-place="top" v-model="tableData" :columns="columns" />
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为excel文件</Button>
      <Button style="position:absolute; top: 27px; right: 17px;" type="primary" @click="addMachineGroup">新增用户</Button>
    </Card>
    <Modal width="1000" v-model="visible" :title="title" :mask-closable="false" @on-ok="okModal" @on-cancel="cancelModal">
      <Row>
        <Col span="12">
        <Row class="row" style="margin-top:0;">
          <Col span="6">
          <strong class="title">
            <strong class="redDot">*</strong>
            用户名称：
          </strong>
          </Col>
          <Col span="18">
          <Input class="form" v-model="userName" placeholder="请输入用户名称" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">
            <strong class="redDot">*</strong>
            所属角色：
          </strong>
          </Col>
          <Col span="18">
          <Select class="form" v-model="role" placeholder="请选择所属角色">
            <Option v-for="item in roleNameList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">
            <strong class="redDot">*</strong>
            电话号码：
          </strong>
          </Col>
          <Col span="18">
          <Input class="form" v-model="phoneNumber" placeholder="请输入电话号码" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">是否启用：</strong>
          </Col>
          <Col span="18">
          <Select v-model="starUse" placeholder="请选择是否启用" class="form">
            <Option :value="0" key="0">启用</Option>
            <Option :value="1" key="1">未启用</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">
            <strong class="redDot">*</strong>
            用户组：
          </strong>
          </Col>
          <Col span="18">
          <Select v-model="userGroup" placeholder="请选择用户组" class="form">
            <Option v-for="item in userGroupNames" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        </Col>
        <Col span="12">
        <Row class="row" style="margin-top: 0;">
          <Col span="6">
          <strong class="title">
            <strong class="redDot">*</strong>
            登录账号：
          </strong>
          </Col>
          <Col span="18">
          <Input :disabled="machineGroupIndex!==-1" v-model="account" placeholder="请输入登录账号" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">
            <strong class="redDot">*</strong>
            身份证：
          </strong>
          </Col>
          <Col span="18">
          <Input v-model="idNumber" placeholder="请输入身份证" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">设置密码：</strong>
          </Col>
          <Col span="18">
          <Input v-model="pwd" placeholder="请输入密码" type="password" password class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">E-Mail：</strong>
          </Col>
          <Col span="18">
          <Input v-model="email" placeholder="请输入e-mail" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">籍贯：</strong>
          </Col>
          <Col span="18">
          <Input v-model="nativePlace" placeholder="请输入籍贯" class="form" />
          </Col>
        </Row>
        </Col>
      </Row>
    </Modal>
    <Modal v-model="deleteVisible" @on-ok="handleDelete">
      <p>是否确定删除该条记录？</p>
    </Modal>
    <Modal v-model="resetVisible" @on-ok="handleReset">
      <p>是否确定重置密码该条记录？</p>
    </Modal>
    <Modal v-model="lockVisible" @on-ok="handleLock">
      <p>是否确定{{ tableData[lockIndex] ? tableData[lockIndex].isLock ? '解锁' : '锁定' : '' }}该条记录？</p>
    </Modal>
  </div>
</template>

<script>
import Tables from '_c/tables'
import rcRequest from 'rc-request'
import jsCookie from 'js-cookie'

export default {
  name: 'role_management_page',
  components: {
    Tables
  },
  data() {
    return {
      columns: [
        { title: '用户名称', key: 'userName' },
        { title: '登录账号', key: 'account' },
        { title: '电话号码', key: 'phoneNumber' },
        { title: 'E-Mail', key: 'email' },
        { title: '微信公众号权限', key: 'authority' },
        {
          title: '操作',
          key: 'action',
          width: 230,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.title = '修改用户';
                    this.visible = true;
                    this.userName = params.row.userName;
                    this.role = params.row.role;
                    this.phoneNumber = params.row.phoneNumber;
                    this.starUse = params.row.starUse;
                    this.userGroup = params.row.userGroup;
                    this.account = params.row.account;
                    this.idNumber = params.row.idNumber;
                    this.email = params.row.email;
                    this.nativePlace = params.row.nativePlace;
                    this.authority = params.row.authority;
                    this.pwd = params.row.pwd;
                    this.isLock = params.row.isLock;
                    this.machineGroupIndex = params.row.initRowIndex;
                  }
                }
              }, '修改'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.deleteIndex = params.row.initRowIndex;
                    this.deleteVisible = true;
                  }
                },
              }, '删除'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.lockIndex = params.row.initRowIndex;
                    this.lockVisible = true;
                  }
                },
              }, params.row.isLock ? '解锁' : '锁定'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.resetIndex = params.row.initRowIndex;
                    this.resetVisible = true;
                  }
                },
              }, '密码重置'),
            ]);
          }
        }
      ],
      tableData: [],
      roleNameList: [],
      userGroupNames: [],
      // 新增/修改用户
      title: '新增用户',
      visible: false,
      userName: '',
      role: '',
      phoneNumber: '',
      starUse: '',
      userGroup: '',
      account: '',
      pwd: '',
      idNumber: '',
      email: '',
      nativePlace: '',
      authority: '',
      isLock: false,
      machineGroupIndex: -1,
      // 删除
      deleteVisible: false,
      deleteIndex: 0,
      // 重置密码
      resetVisible: false,
      resetIndex: 0,
      // 锁定/解锁
      lockVisible: false,
      lockIndex: 0,
    }
  },
  methods: {
    exportExcel() {
      this.$refs.tables.exportCsv({
        filename: `用户-${(new Date()).valueOf()}.csv`
      })
    },
    addMachineGroup() {
      this.title = '新增用户';
      this.visible = true;
      this.userName = '';
      this.role = '';
      this.phoneNumber = '';
      this.starUse = '';
      this.userGroup = '';
      this.account = '';
      this.pwd = '';
      this.idNumber = '';
      this.email = '';
      this.nativePlace = '';
      this.authority = '';
      this.isLock = false,
      this.machineGroupIndex = -1;
    },
    async okModal() {
      if (this.userName.length === 0) {
        this.$Message.error('用户名称不能为空！');
        return;
      }

      if (this.role.length === 0) {
        this.$Message.error('所属角色不能为空！');
        return;
      }

      if (this.phoneNumber.length === 0) {
        this.$Message.error('电话号码不能为空！');
        return;
      }

      if (this.userGroup.length === 0) {
        this.$Message.error('用户组不能为空！');
        return;
      }

      if (this.account.length === 0) {
        this.$Message.error('登录账号不能为空！');
        return;
      }

      if (this.idNumber.length === 0) {
        this.$Message.error('身份证不能为空！');
        return;
      }

      // 新增
      if (this.machineGroupIndex < 0) {
        await rcRequest({
          method: 'post',
          url: '/user/insert_user_info',
          data: {
            user_name: this.userName,
            role_id: this.role,
            phone: this.phoneNumber,
            is_use: this.starUse,
            user_group_id: this.userGroup,
            account: this.account,
            password: this.pwd,
            id_card: this.idNumber,
            email: this.email,
            native_place: this.nativePlace,
            role_id: this.role,
          },
        })
        this.getListData()
        this.$Message.success('新增成功')
        return;
      }

      // 修改
      await rcRequest({
        method: 'post',
        url: '/user/update_user_info',
        data: {
          user_id: this.tableData[this.machineGroupIndex].id,
          user_name: this.userName,
          role_id: this.role,
          phone: this.phoneNumber,
          is_use: this.starUse,
          user_group_id: this.userGroup,
          account: this.account,
          password: this.pwd,
          id_card: this.idNumber,
          email: this.email,
          native_place: this.nativePlace,
          role_id: this.role,
        },
      })
      this.getListData()
      this.$Message.success('修改成功')
    },
    cancelModal() { },
    // 获取列表数据
    async getListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/user/select_user_list',
        data: { }
      })
      this.tableData = data.map(item => ({
        id: item.id,
        userName: item.user_name,
        role: item.role_id,
        phoneNumber: item.phone,
        starUse: item.is_use,
        userGroup: item.user_group_id,
        account: item.account,
        idNumber: item.id_card,
        email: item.email,
        nativePlace: item.native_place,
        authority: item.wechat_public_account_name,
        isLock: item.is_use,
        pwd: item.password,
      }))
    },
    // 获取角色列表数据
    async getRoleListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/role/select_role_list',
        data: { }
      })
      this.roleNameList = data.map(item => ({
        value: item.id,
        label: item.name,
      }))
    },
    // 获取用户组列表数据
    async getUserGroupListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/usergroup/select_user_group_list',
        data: { }
      })
      this.userGroupNames = data.map(item => ({
        value: item.id,
        label: item.name,
      }))
    },
    // 删除数据
    async handleDelete() {
      await rcRequest({
        method: 'post',
        url: '/user/delete_user_info',
        data: { user_id: this.tableData[this.deleteIndex].id },
      })
      this.tableData.splice(this.deleteIndex, 1)
      this.$Message.success('删除成功')
    },
    // 重置密码
    async handleReset() {
      await rcRequest({
        method: 'post',
        url: '/user/update_user_password',
        data: { user_id: this.tableData[this.resetIndex].id },
      })
      this.$Message.success('密码重置成功')
    },
    // 锁定/解锁
    async handleLock() {
      await rcRequest({
        method: 'post',
        url: '/user/update_user_is_use',
        data: { 
          user_id: this.tableData[this.lockIndex].id,
          is_use: !this.tableData[this.lockIndex].isLock ? 1 : 0,
        },
      })
      this.$Message.success(`${this.tableData[this.lockIndex].isLock ? '解锁' : '锁定'}成功`)
      this.tableData[this.lockIndex].isLock = !this.tableData[this.lockIndex].isLock;
    },
  },
  mounted() {
    this.getListData()
    this.getRoleListData()
    this.getUserGroupListData()
  }
}
</script>

<style scoped>
.row {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.redDot {
  color: red;
}

.title {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.form {
  width: 85%;
}
</style>
